import { useMemo, useState } from 'react'
import {
  Card,
  Row,
  Col,
  Progress,
  Typography,
  Empty,
  Select,
  DatePicker,
  Input,
  Button,
  Space,
} from 'antd'
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts'
import {
  ClockCircleOutlined,
  ProjectOutlined,
  CalendarOutlined,
  UserOutlined,
  ClearOutlined,
  SearchOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import {
  isWorkday as isWorkdayUtil,
  getRequiredHours,
} from '../utils/holidayUtils'

// 扩展 dayjs 插件
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)

const { Text } = Typography
const { RangePicker } = DatePicker
const { Option } = Select

const Statistics = ({ data = [], originalData = [], onFilterData }) => {
  const [filters, setFilters] = useState({
    keyword: '',
    project: 'all',
    product: 'all',
    dateRange: null,
  })

  // 获取筛选选项
  const filterOptions = useMemo(() => {
    const projects = [
      ...new Set(originalData.map((item) => item.project || '未分类')),
    ]
    const products = [
      ...new Set(originalData.map((item) => item.product || '未分类')),
    ]

    return { projects, products }
  }, [originalData])

  // 处理筛选
  const handleFilter = () => {
    if (onFilterData) {
      onFilterData(filters)
    }
  }

  // 重置筛选
  const handleResetFilter = () => {
    const resetFilters = {
      keyword: '',
      project: 'all',
      product: 'all',
      dateRange: null,
    }
    setFilters(resetFilters)
    if (onFilterData) {
      onFilterData(resetFilters)
    }
  }

  // 工作日识别函数（支持节假日）
  const isWorkday = (date) => {
    return isWorkdayUtil(date)
  }

  // 计算日期范围内的工作日数量和期望工时
  const calculateWorkdaysAndExpectedHours = (startDate, endDate) => {
    let workdays = 0
    let expectedHours = 0
    let current = dayjs(startDate)
    const end = dayjs(endDate)

    while (current.isSameOrBefore(end, 'day')) {
      const dateStr = current.format('YYYY-MM-DD')
      if (isWorkday(dateStr)) {
        workdays++
        expectedHours += getRequiredHours(dateStr)
      }
      current = current.add(1, 'day')
    }

    return { workdays, expectedHours }
  }

  // 计算统计数据
  const statistics = useMemo(() => {
    // 优先使用filters.dateRange作为统计区间
    let minDate = null
    let maxDate = null
    let workdaysCount = 0
    let expectedHours = 0

    // 判断filters.dateRange是否存在且合法
    if (
      filters.dateRange &&
      Array.isArray(filters.dateRange) &&
      filters.dateRange.length === 2 &&
      filters.dateRange[0] &&
      filters.dateRange[1]
    ) {
      minDate = dayjs(filters.dateRange[0]).format('YYYY-MM-DD')
      maxDate = dayjs(filters.dateRange[1]).format('YYYY-MM-DD')
    } else {
      // 回退到任务数据的最小/最大日期
      data.forEach((item) => {
        if (!item.date) return
        const itemDate = item.date
        if (!minDate || itemDate < minDate) minDate = itemDate
        if (!maxDate || itemDate > maxDate) maxDate = itemDate
      })
    }

    if (minDate && maxDate) {
      const result = calculateWorkdaysAndExpectedHours(minDate, maxDate)
      workdaysCount = result.workdays
      expectedHours = result.expectedHours
    }

    // 总工时和记录数
    const totalHours = data.reduce((sum, item) => sum + (item.hours || 0), 0)
    const totalRecords = data.length
    const averageHours = totalHours / (totalRecords || 1)

    // 按项目统计
    const projectMap = new Map()
    data.forEach((item) => {
      const project = item.project || '未分类'
      if (!projectMap.has(project)) {
        projectMap.set(project, { name: project, hours: 0, count: 0 })
      }
      const projectData = projectMap.get(project)
      projectData.hours += item.hours || 0
      projectData.count += 1
    })
    const projectStats = Array.from(projectMap.values()).sort(
      (a, b) => b.hours - a.hours
    )

    // 按月份统计
    const monthMap = new Map()
    data.forEach((item) => {
      if (!item.date) return
      const month = item.date.substring(0, 7) // YYYY-MM
      if (!monthMap.has(month)) {
        monthMap.set(month, { month, hours: 0, count: 0 })
      }
      const monthData = monthMap.get(month)
      monthData.hours += item.hours || 0
      monthData.count += 1
    })
    const monthlyStats = Array.from(monthMap.values()).sort((a, b) =>
      a.month.localeCompare(b.month)
    )

    // 按产品统计
    const productMap = new Map()
    data.forEach((item) => {
      const product = item.product || '未分类'
      if (!productMap.has(product)) {
        productMap.set(product, { name: product, hours: 0, count: 0 })
      }
      const productData = productMap.get(product)
      productData.hours += item.hours || 0
      productData.count += 1
    })
    const productStats = Array.from(productMap.values()).sort(
      (a, b) => b.hours - a.hours
    )

    // 按日期统计（最近7天）
    const today = dayjs().endOf('day')
    const sevenDaysAgo = dayjs().subtract(7, 'day').startOf('day')
    const dailyMap = new Map()

    data.forEach((item) => {
      if (!item.date) return
      const itemDate = dayjs(item.date)
      if (
        itemDate.isSameOrAfter(sevenDaysAgo) &&
        itemDate.isSameOrBefore(today)
      ) {
        const dateStr = item.date
        if (!dailyMap.has(dateStr)) {
          dailyMap.set(dateStr, { date: dateStr, hours: 0, count: 0 })
        }
        const dailyData = dailyMap.get(dateStr)
        dailyData.hours += item.hours || 0
        dailyData.count += 1
      }
    })
    const dailyStats = Array.from(dailyMap.values()).sort((a, b) =>
      a.date.localeCompare(b.date)
    )

    // 计算缺少的工时
    const missingHours = Math.max(0, expectedHours - totalHours)

    // 计算完成率
    const completionRate =
      expectedHours > 0 ? (totalHours / expectedHours) * 100 : 0

    return {
      totalHours: Math.round(totalHours * 10) / 10,
      totalRecords,
      averageHours: Math.round(averageHours * 10) / 10,
      projectStats,
      monthlyStats,
      dailyStats,
      productStats,
      expectedHours: Math.round(expectedHours * 10) / 10,
      missingHours: Math.round(missingHours * 10) / 10,
      workdays: workdaysCount,
      completionRate: Math.round(completionRate * 10) / 10,
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, filters])

  // 饼图颜色
  const COLORS = [
    '#8884d8',
    '#82ca9d',
    '#ffc658',
    '#ff7300',
    '#00ff00',
    '#ff00ff',
    '#00ffff',
  ]

  if (!data || data.length === 0) {
    return <Empty description='暂无数据' style={{ padding: '40px' }} />
  }

  return (
    <div>
      {/* 筛选器 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16}>
          <Col xs={24} sm={8} md={6}>
            <Input
              placeholder='搜索工作内容'
              value={filters.keyword}
              onChange={(e) =>
                setFilters({ ...filters, keyword: e.target.value })
              }
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col xs={24} sm={8} md={6}>
            <Select
              placeholder='选择项目'
              value={filters.project}
              onChange={(value) => setFilters({ ...filters, project: value })}
              style={{ width: '100%' }}
            >
              <Option value='all'>所有项目</Option>
              {filterOptions.projects.map((project) => (
                <Option key={project} value={project}>
                  {project}
                </Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} sm={8} md={6}>
            <Select
              placeholder='选择产品'
              value={filters.product}
              onChange={(value) => setFilters({ ...filters, product: value })}
              style={{ width: '100%' }}
            >
              <Option value='all'>所有产品</Option>
              {filterOptions.products.map((product) => (
                <Option key={product} value={product}>
                  {product}
                </Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} sm={24} md={6}>
            <Space>
              <Button
                type='primary'
                onClick={handleFilter}
                icon={<SearchOutlined />}
              >
                筛选
              </Button>
              <Button onClick={handleResetFilter} icon={<ClearOutlined />}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
        <Row gutter={16} style={{ marginTop: '16px' }}>
          <Col span={24}>
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              value={filters.dateRange}
              onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
              style={{ width: '100%', maxWidth: '300px' }}
            />
          </Col>
        </Row>
      </Card>

      {/* 基础统计卡片 */}
      <div className='stats-grid'>
        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <ClockCircleOutlined
              style={{
                fontSize: '24px',
                color: '#1890ff',
                marginBottom: '8px',
              }}
            />
            <div className='stat-value'>{statistics.totalHours}h</div>
            <div className='stat-label'>总工时</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <CalendarOutlined
              style={{
                fontSize: '24px',
                color: '#52c41a',
                marginBottom: '8px',
              }}
            />
            <div className='stat-value'>{statistics.totalRecords}</div>
            <div className='stat-label'>总记录数</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <UserOutlined
              style={{
                fontSize: '24px',
                color: '#fa8c16',
                marginBottom: '8px',
              }}
            />
            <div className='stat-value'>{statistics.averageHours}h</div>
            <div className='stat-label'>平均工时</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <ProjectOutlined
              style={{
                fontSize: '24px',
                color: '#eb2f96',
                marginBottom: '8px',
              }}
            />
            <div className='stat-value'>{statistics.projectStats.length}</div>
            <div className='stat-label'>项目数量</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <CalendarOutlined
              style={{
                fontSize: '24px',
                color: '#722ed1',
                marginBottom: '8px',
              }}
            />
            <div className='stat-value'>{statistics.workdays}</div>
            <div className='stat-label'>工作日数</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <CheckCircleOutlined
              style={{
                fontSize: '24px',
                color: '#13c2c2',
                marginBottom: '8px',
              }}
            />
            <div className='stat-value'>{statistics.expectedHours}h</div>
            <div className='stat-label'>期望工时</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <ExclamationCircleOutlined
              style={{
                fontSize: '24px',
                color: statistics.missingHours > 0 ? '#ff4d4f' : '#52c41a',
                marginBottom: '8px',
              }}
            />
            <div
              className='stat-value'
              style={{
                color: statistics.missingHours > 0 ? '#ff4d4f' : '#52c41a',
              }}
            >
              {statistics.missingHours}h
            </div>
            <div className='stat-label'>缺少工时</div>
          </div>
        </Card>

        <Card className='stat-card'>
          <div style={{ textAlign: 'center' }}>
            <div
              style={{
                fontSize: '24px',
                marginBottom: '8px',
                color:
                  statistics.completionRate >= 100
                    ? '#52c41a'
                    : statistics.completionRate >= 80
                    ? '#fa8c16'
                    : '#ff4d4f',
              }}
            >
              {statistics.completionRate >= 100 ? (
                <CheckCircleOutlined />
              ) : statistics.completionRate >= 80 ? (
                <ExclamationCircleOutlined />
              ) : (
                <WarningOutlined />
              )}
            </div>
            <div
              className='stat-value'
              style={{
                color:
                  statistics.completionRate >= 100
                    ? '#52c41a'
                    : statistics.completionRate >= 80
                    ? '#fa8c16'
                    : '#ff4d4f',
              }}
            >
              {statistics.completionRate}%
            </div>
            <div className='stat-label'>完成率</div>
          </div>
        </Card>
      </div>

      {/* 图表区域 */}
      <Row gutter={[16, 16]}>
        {/* 月度工时趋势 */}
        <Col xs={24} lg={12}>
          <Card title='月度工时趋势' size='small'>
            <ResponsiveContainer width='100%' height={300}>
              <BarChart data={statistics.monthlyStats}>
                <CartesianGrid strokeDasharray='3 3' />
                <XAxis dataKey='month' />
                <YAxis />
                <Tooltip
                  formatter={(value, name) => [
                    name === 'hours' ? `${value}小时` : `${value}条记录`,
                    name === 'hours' ? '工时' : '记录数',
                  ]}
                />
                <Bar dataKey='hours' fill='#8884d8' name='hours' />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>

        {/* 项目工时分布 */}
        <Col xs={24} lg={12}>
          <Card title='项目工时分布' size='small'>
            <ResponsiveContainer width='100%' height={300}>
              <PieChart>
                <Pie
                  data={statistics.projectStats.slice(0, 8)}
                  cx='50%'
                  cy='50%'
                  labelLine={false}
                  label={({ name, percent }) =>
                    `${name}: ${(percent * 100).toFixed(1)}%`
                  }
                  outerRadius={80}
                  fill='#8884d8'
                  dataKey='hours'
                >
                  {statistics.projectStats.slice(0, 8).map((entry, index) => (
                    <Cell
                      key={`cell-${index}`}
                      fill={COLORS[index % COLORS.length]}
                    />
                  ))}
                </Pie>
                <Tooltip formatter={(value) => [`${value}小时`, '工时']} />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>

        {/* 项目详细统计 */}
        <Col xs={24} lg={12}>
          <Card title='项目工时排行' size='small'>
            <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
              {statistics.projectStats.map((project, index) => (
                <div key={project.name} style={{ marginBottom: '16px' }}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      marginBottom: '4px',
                    }}
                  >
                    <Text strong>{project.name}</Text>
                    <Text>
                      {project.hours}h ({project.count}条记录)
                    </Text>
                  </div>
                  <Progress
                    percent={Math.round(
                      (project.hours / statistics.totalHours) * 100
                    )}
                    showInfo={false}
                    strokeColor={COLORS[index % COLORS.length]}
                  />
                </div>
              ))}
            </div>
          </Card>
        </Col>

        {/* 产品工时统计 */}
        <Col xs={24} lg={12}>
          <Card title='产品工时统计' size='small'>
            <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
              {statistics.productStats.map((product, index) => (
                <div key={product.name} style={{ marginBottom: '16px' }}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      marginBottom: '4px',
                    }}
                  >
                    <Text strong>{product.name}</Text>
                    <Text>
                      {product.hours}h ({product.count}条记录)
                    </Text>
                  </div>
                  <Progress
                    percent={Math.round(
                      (product.hours / statistics.totalHours) * 100
                    )}
                    showInfo={false}
                    strokeColor={COLORS[index % COLORS.length]}
                  />
                </div>
              ))}
            </div>
          </Card>
        </Col>

        {/* 工时完成情况对比 */}
        <Col xs={24} lg={12}>
          <Card title='工时完成情况' size='small'>
            <ResponsiveContainer width='100%' height={300}>
              <BarChart
                data={[
                  {
                    name: '工时完成情况',
                    实际工时: statistics.totalHours,
                    期望工时: statistics.expectedHours,
                    缺少工时: statistics.missingHours,
                  },
                ]}
              >
                <CartesianGrid strokeDasharray='3 3' />
                <XAxis dataKey='name' />
                <YAxis />
                <Tooltip formatter={(value, name) => [`${value}小时`, name]} />
                <Bar dataKey='实际工时' fill='#52c41a' />
                <Bar dataKey='期望工时' fill='#1890ff' />
                <Bar dataKey='缺少工时' fill='#ff4d4f' />
              </BarChart>
            </ResponsiveContainer>

            {/* 工时完成情况详情 */}
            <div
              style={{
                marginTop: '16px',
                padding: '12px',
                backgroundColor: '#fafafa',
                borderRadius: '6px',
              }}
            >
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  marginBottom: '8px',
                }}
              >
                <span style={{ color: '#666' }}>数据时间范围:</span>
                <span style={{ fontWeight: 'bold' }}>
                  {statistics.workdays > 0
                    ? `${statistics.workdays} 个工作日`
                    : '暂无数据'}
                </span>
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  marginBottom: '8px',
                }}
              >
                <span style={{ color: '#666' }}>工时完成度:</span>
                <span
                  style={{
                    fontWeight: 'bold',
                    color:
                      statistics.completionRate >= 100
                        ? '#52c41a'
                        : statistics.completionRate >= 80
                        ? '#fa8c16'
                        : '#ff4d4f',
                  }}
                >
                  {statistics.completionRate}%
                </span>
              </div>
              {statistics.missingHours > 0 && (
                <div
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                  <span style={{ color: '#666' }}>建议补充:</span>
                  <span style={{ fontWeight: 'bold', color: '#ff4d4f' }}>
                    {statistics.missingHours}小时
                  </span>
                </div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default Statistics
